const Router = require("koa-router")
const path = require("path")
//读取文件流
const fs = require("fs")
//获取文件名
const sparkMd5 = require("spark-md5")

const utils = require("./utils.cjs")
const requestApi = require("./request.cjs")
//引入路由
const router = new Router()

const TEMP_DIR = path.resolve(__dirname, "temp")
if (!fs.existsSync(TEMP_DIR)) {
  fs.mkdirSync(TEMP_DIR)
}
//获取不到传输的文件
const { koaBody } = require("koa-body")

router.post(
  requestApi.upload,
  koaBody({
    multipart: true, //支持多文件上传
    formidable: {
      onFileBegin: (name, file) => {
        //如果不会自动做上传内容重复处理的，可以自己进行判断
        file.filepath = path.join(
          __dirname,
          `./upload/${file.originalFilename}`
        )
      },
      onError: (error) => {
        //上传失败处理
      },
    },
  }),
  (ctx) => {
    const files = ctx.request.files.uploadFile

    let bitmap = fs.readFileSync(
      path.resolve(__dirname, `./upload/${files.originalFilename}`)
    )
    const base64 = `data:text/css;base64,${Buffer.from(bitmap).toString(
      "base64"
    )}`

    //读取文件并且保存文件
    ctx.response.body = {
      status: true,
      message: "操作成功",
      result: {
        fileName: files.newFilename,
        file: base64,
      },
    }
  }
)

router.post(
  requestApi.uploadChunks,
  // koaBody({
  //   multipart: true,
  //   formidable: {
  //     // 上传存放的路劲
  //     uploadDir: path.join(__dirname, "./upload"),
  //     // 保持后缀名\
  //     keepExtensions: true,
  //     // 文件大小
  //     // maxFileSize: 5000,
  //     onFileBegin: (name, file) => {
  //       // 获取后缀, 如: .js  .txt
  //       const reg = /\.[A-Za-z]+$/g
  //       const ext = file.name.match(reg)[0]

  //       //修改上传文件名
  //       file.path = path.join(__dirname, "./upload/") + Date.now() + ext
  //     },
  //     onError(err) {
  //       console.log(err)
  //     },
  //   },
  // }),
  async (ctx, next) => {
    let params = []
    ctx.req.on("data", (chunk) => {
      console.log(chunk)
      // params.push(chunk)
      // let buffer = Buffer.concat(params)
    })
    ctx.req.on("end", (chunk) => {
      const spark = new sparkMd5.ArrayBuffer()
      spark.append(chunk)
      const fileName = spark.end()
      let buffer = Buffer.concat(params)
      fs.writeFileSync(path.join(__dirname, `./upload/${fileName}`))
    })
    const files = ctx.request.files
    const fileName = ctx.request.body.fileName
    const folder = fileName.split("-")[0]
    let filePath = files.chunk.filepath
    let index = filePath.indexOf("upload")
    filePath = filePath.slice(0, index + 8) + `${folder}\\${fileName}`
    //创建文件夹
    const isExists = await utils.exists(
      path.join(__dirname, `./upload/${folder}`)
    )
    // console.log(path.join(__dirname, `./upload/${folder}`))
    if (!isExists) {
      fs.mkdir(path.join(__dirname, 0777, `./upload/${folder}`), (err) => {
        if (err) throw err
        //读取文件
        const reader = fs.createReadStream(files.chunk.filepath)

        let count = 0
        let str = ""
        reader.on("data", (data) => {
          str += data
          count++
        })
        reader.on("end", () => {
          console.log(path.join(__dirname, `./upload/${folder}/${fileName}`))
          const upStream = fs.createWriteStream(
            path.join(__dirname, `./upload/${folder}/${fileName}`)
          )
          upStream.write(str)
          upStream.end()
          upStream.on("finish", () => {
            console.log("写入完成")
          })
        })
      })
    } else {
      const reader = fs.createReadStream(files.chunk.filepath)

      let count = 0
      let str = ""
      reader.on("data", (data) => {
        str += data
        count++
      })
      reader.on("end", () => {
        console.log(path.join(__dirname, `./upload/${folder}/${fileName}`))
        const upStream = fs.createWriteStream(
          path.join(__dirname, `./upload/${folder}/${fileName}`)
        )
        upStream.write(str)
        upStream.end()
        upStream.on("finish", () => {
          console.log("写入完成")
        })
      })
    }
    ctx.response.body = {
      status: true,
      message: "写入完成",
      result: null,
    }
    // files.forEach((item) => {
    //   const reader = path.join(__dirname, `./upload/${folder}`)
    // })
    // try {
    //   let { files } = await utils.multipartyUpload(ctx.req, true)
    //   let file = files && files.file.length ? files.file[0] : {}
    //   ctx.body = {
    //     code: 0,
    //     message: "文件上传成功",
    //     originalFilename: file.originalFilename,
    //     serverPath: file.path.replace(__dirname, HOSTNAME),
    //   }
    // } catch (error) {
    //   ctx.body = {
    //     code: 1,
    //     message: "文件上传失败",
    //   }
    // }
    // if (ctx.request.files) {
    //   //根据文件生成一个名字
    //   const files = ctx.request.files
    //   const fileName = ctx.request.body.fileName
    //   //创建文件夹
    //   const folder = fileName.split("-")[0]
    //   //修改filepath
    //   let filePath = files.chunk.filepath
    //   let index = filePath.indexOf("upload")
    //   filePath = filePath.slice(0, index + 8) + `${folder}\\${fileName}`
    //   fs.stat(
    //     path.resolve(__dirname, `./upload/${folder}`),
    //     function (err, stats) {
    //       if (!stats) {
    //         fs.mkdir(
    //           path.join(__dirname, `./upload/${folder}`),
    //           { recursive: true },
    //           (err) => {
    //             if (err) throw err
    //             //保存文件操作
    //             const buff = Buffer.from(files.chunk)
    //             fs.open(
    //               path.join(`${filePath}\\${fileName}`),
    //               function (err, fd) {
    //                 if (err) {
    //                   console.log(err)
    //                 }
    //                 fs.write(fs, buff, function (err) {})
    //                 fs.close()
    //               }
    //             )
    //           }
    //         )
    //       }
    //     }
    //   )
    // }
    // ctx.response.body = {
    //   status: true,
    //   message: "操作失败",
    //   result: null,
    // }
  }
)

//合并文件
router.post(requestApi.mergeFiles, async (ctx, next) => {
  const fileName = ctx.request.body.fileName.split("-")[0]

  const fileArr = Number(ctx.request.body.fileName.split("-")[1])
  //读取改文件夹下得文件
  const filePath = path.join(__dirname, `./upload/${fileName}`)

  fs.readdir(filePath, async function (err, files) {
    if (err) throw err
    if (files.length !== fileArr) {
      ctx.response.body = {
        message: "文件长度不一致",
        status: false,
      }
    }
    files.sort().forEach((filename, index) => {
      const fullFilePath = path.join(filePath, filename)

      fs.stat(fullFilePath, (err, stats) => {
        if (err) throw err
        const isFile = stats.isFile()
        if (isFile) {
          fs.appendFileSync(
            path.join(__dirname, `./upload/${fileName}-full.png`),
            fs.readFileSync(
              path.join(
                __dirname,
                `./upload/${fileName}/${fileName}-${index + 1}`
              )
            )
          )
          fs.unlinkSync(
            path.join(
              __dirname,
              `./upload/${fileName}/${fileName}-${index + 1}`
            )
          )
          // let count = 0
          // let str = ""
          // reader.on("data", (data) => {
          //   str += data
          //   count++
          // })
          // reader.on("end", () => {
          //   console.log(
          //     path.join(__dirname, `./upload/${fileName}/${fileName}`)
          //   )
          //   const upStream = fs.createWriteStream(
          //     path.join(__dirname, `./upload/${fileName}/${fileName}`)
          //   )
          //   upStream.write(str)
          //   upStream.end()
          //   upStream.on("finish", () => {
          //     console.log("写入完成")
          //   })
          // })
        }
      })
    })

    // setTimeout(() => {
    //   fs.rmdirSync(path.join(__dirname, `./upload/${fileName}`))
    // }, 1000)

    ctx.response.body = {
      status: true,
      message: "合并完成",
      result: null,
    }
  })
})

//切片上传
router.post(requestApi.uploadChunksNew, async (ctx) => {
  const file = ctx.request.files.chunk
  const fileName = ctx.request.body.fileName

  const chunkPath = path.join(TEMP_DIR, `${fileName}`)
  await fs.promises.copyFile(file.path || file.filepath, chunkPath)
  await fs.promises.unlink(file.path || file.filepath)

  ctx.body = {
    success: true,
  }
})

//合并文件
router.post(requestApi.mergeFilesNew, async (ctx, next) => {
  const fileName = ctx.request.body.fileName.split("-")[0]
  const fileArr = Number(ctx.request.body.fileName.split("-")[1])
  //原始文件名称
  const originFileName = ctx.request.body.originFileName

  const suffix = originFileName.split(".")[1]
  //读取改文件夹下得文件
  const filePath = path.join(__dirname, `./temp`)
  const outputPath = path.join(__dirname, "./upload", fileName)

  fs.readdir(filePath, async function (err, files) {
    if (err) throw err
    if (files.length !== fileArr) {
      ctx.response.body = {
        message: "文件长度不一致",
        status: false,
      }
    }

    files.sort().forEach((filename, index) => {
      const fullFilePath = path.join(filePath, `${filename}`)
      fs.stat(fullFilePath, (err, stats) => {
        if (err) throw err
        const isFile = stats.isFile()
        if (isFile) {
          fs.appendFileSync(
            path.join(__dirname, `./upload/${fileName}.${suffix}`),
            fs.readFileSync(path.join(__dirname, `./temp/${filename}`))
          )
          //合并完之后删除temp下得数据
          fs.unlinkSync(path.join(__dirname, `./temp/${filename}`))
        }
      })
    })

    // setTimeout(() => {
    //   fs.rmdirSync(path.join(__dirname, `./upload/${fileName}`))

    ctx.response.body = {
      status: true,
      message: "合并完成",
      result: null,
    }
  })
})

//断点续传
router.post(requestApi.checkUploaded, async (ctx) => {
  const originalChunkName = ctx.request.body.chunkName
  const chunkPath = path.join(__dirname, `./temp/${originalChunkName}`)
  try {
    await fs.promises.stat(chunkPath, (err, stats) => {
      if (err) throw err
      ctx.response.body = {
        status: true,
        result: true,
      }
    })
  } catch (error) {
    ctx.response.body = {
      status: true,
      result: false,
    }
  }
})
module.exports = router
